var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦？\nnode server.js 8888 这样不会吗？')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看，上面不要看 ************/

  console.log('有个傻子发请求过来啦！路径（带查询参数）为：' + pathWithQuery)

  if(path === '/sign_in'&&method === "POST"){
    response.setHeader('Content-Type','text/html;charset=utf-8')
    const userarray = JSON.parse( fs.readFileSync('./db/users.json'))
    const array =[]
    request.on('data',(chunk)=>{
      array.push(chunk)
    })
    request.on('end',()=>{

      console.log(array);
      const string= Buffer.concat(array).toString()
      console.log(string);
      const obj = JSON.parse(string)
      const user = userarray.find((user)=>user.name===obj.name&&user.password===obj.password)
      console.log(user);
      if(user === undefined){
        console.log(333);
        response.statusCode =400
        response.setHeader("Content-Type","text/json;charset=utf-8")
        response.end(`{"errorCode":4001}`)
      }else{
        response.statusCode =200
        response.setHeader('Set-Cookie',`user_id=${user.id};`)
        // const random=Math.random()
        // const session =JSON.parse(fs.readFileSync('./session.json')).toString()
        // response.setHeader('Set-Cookie',`session_id=${random};HttpOnly`)
        // session[random] = {user_id:user.id}
        // fs.writeFileSync('./session.json',JSON.stringify(session))
        response.end()
      }
      
    })
  }
  else if(path === '/score'&&method === "POST"){
    response.setHeader('Content-Type','text/html;charset=utf-8')
    const userarray = JSON.parse( fs.readFileSync('./db/users.json'))
    const array =[]
    request.on('data',(chunk)=>{
      array.push(chunk)
    })
    request.on('end',()=>{

      console.log(array);
      const string= Buffer.concat(array).toString()
      console.log(string);
      const obj = JSON.parse(string)

      console.log(obj.userid)
      
      const user = userarray.find((user)=>user.id.toString()===obj.userid)
      console.log(userarray);
      console.log(user);
      user.total=obj.total
      // console.log( JSON.parse( fs.readFileSync('./db/score.json')))
      fs.writeFileSync('./db/score.json',JSON.stringify(userarray))
      // if(user === undefined){
      //   console.log(333);
      //   response.statusCode =400
      //   response.setHeader("Content-Type","text/json;charset=utf-8")
      //   response.end(`{"errorCode":4001}`)
      // }else{
        response.statusCode =200
      //   response.setHeader('Set-Cookie',`user_id=${user.id};`)
       
        response.end()
      // }
      
    })
  }

  else if(path === '/index1.html'||path === '/index2.html'||path === '/index4.html'||path === '/index5.html'){
    
    let dex =path.split('.')[0].split('/index')[1];
    
    const cookie = request.headers['cookie']
    let userId
    try {
      userId=cookie.split(';').filter(s =>s.indexOf('user_id=')>=0)[0].split('=')[1]
    } catch (error) {}
      if(userId)
      {
        const userarray = JSON.parse( fs.readFileSync('./db/users.json'))

        const user= userarray.find(user=>user.id.toString()===userId)
        const homehtml= fs.readFileSync(`./public/index${dex}.html`).toString()
        let string
        if(user){
          console.log('456');
          console.log(user);
          console.log(user.name);
          String.prototype.myReplace=function(f,e){//吧f替换成e
            let reg=new RegExp(f,"g"); //创建正则RegExp对象   
            return this.replace(reg,e); 
        }
        // let newstr=homehtml.myReplace('{{user.name}}',user.name);
          // alert(newstr);
           string =homehtml.replace("{{loginStatus}}","已登录").myReplace('{{user.name}}',user.name);
        }else{
          // string =homehtml.replace("{{loginStatus}}","未登录").replace("{{user.name}}",'')
        }
        response.write(string)
        response.end()
      }else{
        const homehtml= fs.readFileSync(`./public/index${dex}.html`).toString();
        string= homehtml.replace("{{loginStatus}}","未登录").replace("{{user.name}}",'')
        response.write(string)
        response.end()
      }
    
 
    // if(cookie&&cookie.indexOf ('logined=1')!=-1){
    //   const homehtml= fs.readFileSync("./public/home.html").toString()
    //   const string = homehtml.replace('{{loginStatus}}','已登录')
    //   response.write(string)
    // }else{
    //   const homehtml= fs.readFileSync("./public/home.html").toString()
    //   const string = homehtml.replace('{{loginStatus}}','未登录').replace('{{user.name}}','')
    //   response.write(string)
    // }
   
  }
  else if(path === '/index3.html'){
    const cookie = request.headers['cookie']
    let userId
    try {
      userId=cookie.split(';').filter(s =>s.indexOf('user_id=')>=0)[0].split('=')[1]
    } catch (error) {}
      if(userId)
      {
        const userarray = JSON.parse( fs.readFileSync('./db/score.json'))
        // console.log(userarray)

        // for(let i=0;i<userarray.length;i++){
        //   console.log(userarray[i])
        // }

        const user= userarray.find(user=>user.id.toString()===userId)
        const homehtml= fs.readFileSync('./public/index3.html').toString()
      //   let string
        if(user){
      //     console.log('456');
      //     console.log(user);
      //     console.log(user.name);
          String.prototype.myReplace=function(f,e){//吧f替换成e
            let reg=new RegExp(f,"g"); //创建正则RegExp对象   
            return this.replace(reg,e); 
        }
        // let newstr=homehtml.myReplace('{{user.name}}',user.name);
          // alert(newstr);
          console.log(user.total)
           string =homehtml.replace("{{1}}",user.name).replace("{{2}}",user.total).replace("{{loginStatus}}","已登录").replace('{{user.name}}',user.name);
        }
        // else{
        //   string =homehtml.replace("{{1}}","未登录").replace("{{2}}",'')
        // }
        response.write(string)
        response.end()
      }else{
        const homehtml= fs.readFileSync("./public/index3.html").toString();
        string= homehtml.replace("{{1}}","未登录").replace("{{2}}",'')
        response.write(string)
        response.end()
      }
    
 
    // if(cookie&&cookie.indexOf ('logined=1')!=-1){
    //   const homehtml= fs.readFileSync("./public/home.html").toString()
    //   const string = homehtml.replace('{{loginStatus}}','已登录')
    //   response.write(string)
    // }else{
    //   const homehtml= fs.readFileSync("./public/home.html").toString()
    //   const string = homehtml.replace('{{loginStatus}}','未登录').replace('{{user.name}}','')
    //   response.write(string)
    // }
   
  }
  else  if(path==="/regis"&&method==="POST"){
    response.setHeader('Content-Type','text/html;charset-utf-8')
    const userarray = JSON.parse( fs.readFileSync('./db/users.json'))
    const array =[]
    request.on('data',(chunk)=>{
      array.push(chunk)
    })
    request.on('end',()=>{
      console.log(array);
      const string= Buffer.concat(array).toString()
      console.log(string);
      const obj = JSON.parse(string)
      const lastuser = userarray[userarray.length-1]
      console.log(obj.name);
      console.log(obj.password);
      const newUser ={id: lastuser?lastuser.id+1:1,name:obj.name,password:obj.password}
      userarray.push(newUser)
      fs.writeFileSync('./db/users.json',JSON.stringify(userarray))
      response.end();
    })
  }else{

  const x =path==='/'?'/index.html':path
  const index= x.lastIndexOf('.')
  const y =x.slice(index+1,x.length)
  const filetype={
      'html':'text/html',
      'css':'text/css',
      'js':'text/javascript',
      'png':'image/png',
      'jpg':'image/jpeg'
  }

  console.log(y);
    response.statusCode = 200
    response.setHeader('Content-Type', `${filetype[y]||'text/html'};charset=utf-8`)
    let content 
    try{
    content= fs.readFileSync(`./public${x}`)
    }catch(error){
        content='文件不存在'
        response.statusCode= 404
    }
    response.write(content)
    response.end()
  } 
  
  /******** 代码结束，下面不要看 ************/
})

server.listen(port)
console.log('监听 ' + port + ' 成功\n请用在空中转体720度然后用电饭煲打开 http://localhost:' + port)